﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MyApplication.User.UserInfo; 
using MyCommon.Middleware;
using MyInfrastructure.Contexts.Discuss.Message;
using MyInfrastructure.Contexts.Discuss.Topics;
using MyInfrastructure.Contexts.Log;
using MyInfrastructure.Contexts.User;
using MyInfrastructure.Repository.User.UserInfo; 

namespace MyApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("any", builder =>
                {
                    builder.AllowAnyOrigin() //允许任何来源的主机访问 
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials();//指定处理cookie
                });
            });

            services.AddSignalR();
            services.AddLogging();
            services.AddScoped<IUserInfoService, UserInfoService>();
            services.AddScoped<IUserInfoRepository, UserInfoRepository>();

            services.AddDbContext<LogInfoContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLConnectString")));
            services.AddDbContext<UserInfoContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLConnectString")));
            services.AddDbContext<TopicsContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLConnectString")));
            services.AddDbContext<MessageInfoContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLConnectString")));

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        { 
            app.UseMiddleware(typeof(ErrorMiddleware)); 
            app.UseMyStatusCode("/error/{0}");
            app.UseCors("any");
            app.UseStaticFiles();
            app.UseMvc();
        }
    }
}
